<style lang="less">

</style>

<template>
  <el-cascader
    :options="options"
    :props="props"
    :disabled="disabled"
    change-on-select
    v-bind:value="value"
    v-on:change="change"
    v-on:input="updateValue($event)">
  </el-cascader>
</template>

<script>
import { addressDictsSimpleWithType } from '../api/system/addressDict';

export default {
  data () {
    return {
      options: this.$store.state.addressDicts,
      props: {
        value: 'id',
        label: 'name'
      }
    };
  },
  props: ['value', 'disabled', 'change-on-select'],
  methods: {
    setAddresses (val) {
      this.$emit('getAddresses', val);
    },
    change (val) {
      this.$emit('change', val);
    },
    updateValue (val) {
      this.$emit('input', val);
    },
    clearEmptyChildren (items) {
      let o = this.clearEmptyChildren;
      items.forEach(function (v) {
        if (v.children.length === 0) {
          delete v.children;
        } else {
          o(v.children);
        }
      });
    },
    searchAddressDicts (reload) {
      if (this.$store.state.addressDicts.length === 0 || reload) {
        addressDictsSimpleWithType('level=1,2,3,4').then(res => {
          let list = res.data.detailModelList;
          this.options = list;
          this.setAddresses(list);
          this.clearEmptyChildren(list);
          this.$store.state.addressDicts = list;
        }).catch(err => {
          console.error(err);
        });
      } else {
        this.$emit('getAddresses', this.$store.state.addressDicts);
      }
    }
  },
  mounted () {
    this.searchAddressDicts(false);
  }
};
</script>
